import {Button, message, Popconfirm} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import UpdateForm from './components/UpdateForm';
import {TableListItem} from './data.d';
import {list, batchCode, code, update, getConfig} from './service';
import {AuthConsumer} from '@/utils/authContent'
import {downLoadFile, MimeEnum} from '@/utils/downLoadFileUtil'
import {EditOutlined} from '@ant-design/icons';

/**
 * 更新
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在更新');
  try {
    const data = await update({...fields});
    hide();
    if (data.code === 1) {
      message.success('更新成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('更新失败,请重试');
    return false;
  }
  message.error('更新失败,请重试');
  return false;
};


/**
 * 生成代码
 * @param record
 */
const handleCode = async (record: TableListItem) => {
  const hide = message.loading('正在生成代码');
  try {
    const data = await code(record.tableName);
    hide();
    if (data != null) {
      downLoadFile(data, "generatorCode.zip", MimeEnum.ZIP);
    }
    return true;
  } catch (error) {
    hide();
    message.error('生成代码失败，请重试');
    return false;
  }
  message.error('生成代码失败，请重试');
  return false;
};

/**
 *  批量生成代码
 * @param selectedRows
 */
const handleBatchCode = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在批量生成代码');
  if (!selectedRows) return true;
  try {
    const tableNames = new Array();
    selectedRows.forEach((row: TableListItem) => {
      tableNames.push(row.tableName);
    })
    const data = await batchCode(tableNames);
    hide();
    if (data != null) {
      downLoadFile(data, "generatorCode.zip", MimeEnum.ZIP);
    }
    return true;
  } catch (error) {
    hide();
    message.error('批量生成代码失败，请重试');
    return false;
  }
  message.error('批量生成代码失败，请重试');
  return false;
};


const GeneratorTableList: React.FC<{}> = () => {

  // 更新Model可见性
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  // 设置更新表单值
  const [updateFormValues, setUpdateFormValues] = useState({});
  // 通过actionRef进行表单刷新
  const actionRef = useRef<ActionType>();
  //  选择行数据的状态
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  // 删除生成代码按钮
  const onCodeConfirm = async (record: TableListItem) => {
    await handleCode(record);
    actionRef.current?.reloadAndRest?.();
  }

  // 表头
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '编号',
      dataIndex: 'tableName',
      valueType: 'textarea',
      hideInSearch: true,
      align: "center",
      render: (_, record, index) => {
        return index + 1
      }
    },
    {
      title: '名称',
      dataIndex: 'tableName',
      valueType: 'text',
      copyable: true,
      align: "center",
    },
    {
      title: '注释',
      dataIndex: 'comment',
      valueType: 'text',
      hideInSearch: true,
      align: "center",
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      hideInSearch: true,
      valueType: 'text',
      align: "center",
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: "center",
      render: (_, record) => (
        <>
          <AuthConsumer name={'tool:generator:code'}>
            <Popconfirm
              title="确认需要生成"
              okText="确定"
              cancelText="取消"
              onConfirm={() => onCodeConfirm(record)}
            >
              <a href="#">生成</a>
            </Popconfirm>
          </AuthConsumer>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      {/* 表格 */}
      <ProTable<TableListItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="tableName"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <AuthConsumer name={'tool:generator:update'}>
            <Button type="primary" onClick={async () => {
              handleUpdateModalVisible(true);
              const data = await getConfig();
              setUpdateFormValues(data.data);
            }}><EditOutlined />
              修改配置
            </Button>
          </AuthConsumer>,

        ]}
        // request = {async (params, sorter, filter) => {
        request={async (params) => {
          console.log(params)
          const data = await list({...params});
          if (data.code === 1) {
            return {
              data: data.data.rows,
              // success请返回true，不然table会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: data.data.total,
            };
          }
          return {
            data: [],
            success: true,
            total: 0,
          }
        }
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />

      {/* 选择数据的状态 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{fontWeight: 600}}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <AuthConsumer name={'tool:generator:batchCode'}>
            <Button danger type={"primary"}
                    onClick={async () => {
                      await handleBatchCode(selectedRowsState);
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }}
            >
              批量生成
            </Button>
          </AuthConsumer>
        </FooterToolbar>
      )}


      {/* 更新表单 */}
      <UpdateForm
        updateModalVisible={updateModalVisible}
        handleUpdateModalVisible={handleUpdateModalVisible}
        updateFormValues={updateFormValues}
        handleUpdate={handleUpdate}
        actionRef={actionRef}
      ></UpdateForm>


    </PageContainer>
  );
};

export default GeneratorTableList;
